package com.ldk.base.framework.util.sms;

import java.net.URLEncoder;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.ldk.base.framework.util.HttpUtil;


/**
 * 云信 短信接口
 * @author xiangwl
 *
 */
public class Sms implements ISmsApi {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	private final static String SMS_URL = "http://api.sms.cn/sms/";
//	private final static String SMS_UID = "dudusulian";
//	private final static String SMS_PASSWORD = "3d539adae6ba49fd81126fce97efeb02";
	private final static String SMS_ENCODE="utf-8";


	@Override
	public Boolean send(SmsConfig config) {
		if(config == null) return false;
		if(StringUtils.isBlank(config.getAccessKey()) ||
		   StringUtils.isBlank(config.getAccessPwd()) ||
		   StringUtils.isBlank(config.getPhonNos()) ||
		   StringUtils.isBlank(config.getContent()))
			return false;
		
		String encodeContent = config.getContent();
		try{
			encodeContent = URLEncoder.encode(config.getContent(), "utf-8");
		}
		catch(Exception e){
			
		}
		String params=String.format("ac=send&uid=%s&pwd=%s&encode=%s&mobile=%s&content=%s",
									config.getAccessKey(),
									config.getAccessPwd(),
									SMS_ENCODE,
									config.getPhonNos(),
									encodeContent);
		
		String result = HttpUtil.get(SMS_URL, params, null);
		System.out.println("SMS::Response::"+result);
		if(StringUtils.isEmpty(result))
			return false;
		try{
			SmsResponse response = JSON.parseObject(result, SmsResponse.class);
			if(response.getStat().equals("100")){
				return true;
			}
			else{
				logger.error(response.getStat() + ":" + response.getMessage());
			}
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		
		if(result.contains("\"stat\":\"100\""))
			return true;
		
		return false;
	}
	
	/**
	 * 云信响应对象
	 * @author xiangwl
	 *
	 */
	protected class SmsResponse{
		/**
		 * stat=100为成功
		 */
		private String stat;
		private String message;
		
		public String getMessage() {
			return message;
		}
		public String getStat() {
			return stat;
		}
		public void setStat(String stat) {
			this.stat = stat;
		}
		public void setMessage(String message) {
			this.message = message;
		}
	}

}
